package com.studyyoun.android.androidcommonbaselibrary.okhttp.callback;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.exce.OkhttpException;
import com.studyyoun.android.androidcommonbaselibrary.utils.FastJsonUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by androidlongs on 17/6/28.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

public abstract class OkhttpCommonCallBack implements Callback {

    private Class<?> mTClass;
    private Handler mHandler;
    private boolean mIsList = false;

    public OkhttpCommonCallBack() {

        mHandler = new Handler(Looper.getMainLooper());
    }

    public OkhttpCommonCallBack(Class<?> clas) {

        mTClass = clas;
        mHandler = new Handler(Looper.getMainLooper());
    }


    @Override
    public void onFailure(Call call, final IOException e) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                onFaile(new OkhttpException(e.getMessage(), -1));
            }
        });

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {

        final String string = response.body().string();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                handlerSuccessResult(string);
            }
        });
    }

    /**
     * 处理请求响应成功结果
     */
    private void handlerSuccessResult(String string) {

        if (TextUtils.isEmpty(string)) {
            onFaile(new OkhttpException("请求异常", -1));
        } else {
            try {


                if (mTClass == null) {
                    onSuccess(string);
                } else {
                    if (string.startsWith("{") && string.endsWith("}")) {

                        Object o = FastJsonUtil.toBean(string, mTClass);
                        onSuccess(o);
                    } else if (string.startsWith("[") && string.endsWith("]")) {
                        List<?> objects = FastJsonUtil.toList(string, mTClass);
                        onSuccess(objects);
                    } else {
                        onFaile("class is null");
                    }
                }
            } catch (Exception e) {
                onFaile(new OkhttpException("网络异常 "+e.getMessage(), -2));
            }
        }
    }


    /**
     * 请求成功回调方法
     */
    public abstract void onSuccess(Object obj);

    /**
     * 请求失败回调方法
     */
    public abstract void onFaile(Object obj);

}
